import json
from operator import length_hint

from pyecharts.charts import Bar, Timeline
from pyecharts import options as opts

try:
    # 读取数据文件
    with open(r"D:\itheima\Python\可视化案例数据\动态柱状图数据\1960-2019全球GDP数据.csv", "r", encoding="GB2312") as f:
        data_lines = f.readlines()

    # 去除第一行表头
    if data_lines:
        data_lines.pop(0)

    # 将数据转为字典存储
    data_dict = {}
    for line in data_lines:
        parts = line.strip().split(",")
        if len(parts) < 3:
            continue  # 跳过格式不正确的行

        try:
            year = int(parts[0])
            country = parts[1]
            gdp = float(parts[2])

            if year not in data_dict:
                data_dict[year] = []
            data_dict[year].append([country, gdp])
        except (ValueError, IndexError) as e:
            print(f"数据解析错误，跳过此行: {line.strip()}, 错误: {str(e)}")
            continue

    if not data_dict:
        raise ValueError("没有有效的GDP数据")

    # 创建时间轴
    timeline = Timeline(init_opts=opts.InitOpts(width="1200px", height="600px"))

    # 按年份排序
    sorted_years = sorted(data_dict.keys())

    for year in sorted_years:
        # 按GDP降序排序并取前8名
        sorted_data = sorted(data_dict[year], key=lambda x: x[1], reverse=True)[:8]

        countries = [item[0] for item in sorted_data]
        gdp_values = [round(item[1] / 100000000, 2) for item in sorted_data]  # 转换为亿单位并保留2位小数

        # 创建柱状图
        bar = Bar()
        countries.reverse()
        gdp_values.reverse()
        bar.add_xaxis(countries)
        bar.add_yaxis(
            series_name="GDP(亿)",
            y_axis=gdp_values,
            label_opts=opts.LabelOpts(
                is_show=True,
                position="right",
                formatter="{@[1]}亿"
            ),
            itemstyle_opts=opts.ItemStyleOpts(color="#5793f3")
        )

        # 设置全局选项
        bar.set_global_opts(
            title_opts=opts.TitleOpts(
                title=f"{year}年全球GDP前8国家",
                subtitle="单位: 亿美元",
                pos_left="center"
            ),
            legend_opts=opts.LegendOpts(is_show=False),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=45)),
            yaxis_opts=opts.AxisOpts(name="GDP(亿)"),
            graphic_opts=[opts.GraphicGroup(
                graphic_item=opts.GraphicItem(
                    right="5%",
                    bottom="10%"
                )
            )]
        )

        bar.reversal_axis()

        # 添加到时间轴
        timeline.add(bar, str(year))

    # 配置时间轴选项
    timeline.add_schema(
        play_interval=800,
        is_auto_play=True,
        is_loop_play=True,
        is_timeline_show=True,
        pos_left="10%",
        pos_right="10%",
        symbol_size=8,
        linestyle_opts=opts.LineStyleOpts(width=4)
    )

    # 渲染图表
    timeline.render("global_gdp_timeline.html")
    print("动态GDP图表生成成功，已保存为 global_gdp_timeline.html")

except FileNotFoundError:
    print("错误: 数据文件未找到，请检查文件路径")
except Exception as e:
    print(f"发生错误: {str(e)}")